from profiler.profiler import *
from datetime import datetime, timedelta

class HecateEvent:
	def __init__(self, app_id, event_id, callback, tags, update_interval, give_objs):
		self.app_id = app_id
		self.event_id = event_id
		self.callback = callback
		self.tags = tags
		self.update_interval = update_interval
		self.give_objs = give_objs
		#self.last_checked = datetime.now()

class HecateTimeEvent(HecateEvent):
	def __init__(self, app_id, event_id, callback, tags, time_interval=900, update_interval=30, give_objs=True):
		HecateEvent.__init__(self, app_id, event_id, callback, tags, update_interval, give_objs)
		self.time_interval = time_interval

class HecateLocationEvent(HecateEvent):
	def __init__(self, app_id, event_id, callback, tags, dist=0.036, update_interval=30, give_objs=True):
		HecateEvent.__init__(self, app_id, event_id, callback, tags, update_interval, give_objs)
		self.dist = dist

class HecateNotifier:
	wakeups = {}

	def CheckAppEvents(self, app_id, location_stamp, time_stamp):
		"""
		CheckEvents:  looks at all of the stored events and checks if their associated callbacks should be invoked
		"""
		if not HecateNotifier.wakeups.has_key(app_id):
			return False

		p = HecateProfiler(app_id)
		triggered_event = False
	
		for event_id in HecateNotifier.wakeups[app_id]:
			event = HecateNotifier.wakeups[app_id][event_id]

			if True:#time_stamp - event.last_checked >= timedelta(seconds=event.update_interval):
				#Check for wakeup here
				#print "Event " + event.event_id + " from application " + str(event.app_id) + " needs to be checked!"

				tags = []

				for tag in event.tags:
					if hasattr(event, "dist"):
						if p.LocationSatisfiesThreshold(location_stamp, tag, event.dist):
							tags.append(tag)
					if hasattr(event, "time_interval"):
						if p.TimeSatisfiesThreshold(time_stamp, tag, event.time_interval):
							tags.append(tag)
						
				if event.give_objs and len(tags) > 0:
					print "BLAH" + str(p.PopularObjectsForTags(tags))
					event.callback(p.PopularObjectsForTags(tags))
				elif len(tags) > 0:
					event.callback(tags)
				else:
					event.callback(None)

				event.last_checked = time_stamp
				triggered_event = True

		return triggered_event

	def RegisterEvent(self, event):
		"""
		RegisterWakeup: allow apps to register a callback with an event
		"""
		if HecateNotifier.wakeups.has_key(event.app_id):
			if not HecateNotifier.wakeups[event.app_id].has_key(event.event_id):
				HecateNotifier.wakeups[event.app_id][event.event_id] = event
		else:
			HecateNotifier.wakeups[event.app_id] = {}
			HecateNotifier.wakeups[event.app_id][event.event_id] = event

